package com.ruoyi.fire.service.impl;

import java.util.*;
import java.util.concurrent.Executor;
import java.util.stream.Collectors;

import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.common.core.domain.ResponseEntityInfo;
import com.ruoyi.common.core.domain.entity.SysDictData;
import com.ruoyi.common.enums.*;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.*;
import com.ruoyi.fire.domain.*;
import com.ruoyi.fire.mapper.TDeviceMapper;
import com.ruoyi.fire.service.IDGatewayMessageService;
import com.ruoyi.fire.service.IDWaterMessageService;
import com.ruoyi.fire.service.ITUnitService;
import com.ruoyi.system.service.ISysDictTypeService;
import io.swagger.models.auth.In;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.fire.mapper.TDeviceMapper;
import com.ruoyi.fire.service.ITDeviceService;
import org.springframework.util.CollectionUtils;

/**
 * 设备信息Service业务层处理
 *
 * @author ruoyi
 * @date 2025-11-05
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class TDeviceServiceImpl extends ServiceImpl<TDeviceMapper, TDevice> implements ITDeviceService {
    @Autowired
    private TDeviceMapper tDeviceMapper;

    private final ITUnitService unitService;
    private final RequestService requestService;
    // 添加线程池注入
    private final Executor threadPoolTaskExecutor;
    private final IDGatewayMessageService gatewayMessageService;
    private final IDWaterMessageService waterMessageService;
    private final ISysDictTypeService dictTypeService;


    // 静态常量提取，避免重复创建
    private static final List<String> GATEWAY_FAULT_TYPES = Arrays.asList("电源故障", "主电故障", "备电故障", "通讯故障", "故障");
    private static final List<String> GATEWAY_RESET_TYPES = Arrays.asList("复位", "故障恢复", "主电故障恢复", "备电故障恢复", "备电恢复", "恢复", "主电恢复");
    private static final List<String> GATEWAY_OTHER_TYPES = Arrays.asList("消音", "反馈", "消声");
    private static final List<String> GATEWAY_FIRE_TYPES = Arrays.asList("火警", "首次火警", "火灾报警", "火灾后续");

    // 水池/水箱
    private static final Set<String> WATER_POOL_TANK_TYPES = new HashSet<>(Arrays.asList("1", "4"));
    // 消火栓/喷淋
    private static final Set<String> WATER_SYSTEM_TYPES = new HashSet<>(Arrays.asList("2", "3"));
    // 消火栓
    private static final Set<String> HYDRANT_TYPES = new HashSet<>(Collections.singletonList("2"));
    // 喷淋
    private static final Set<String> SPRINKLER_TYPES = new HashSet<>(Collections.singletonList("3"));


    /**
     * 查询设备信息
     *
     * @param id 设备信息主键
     * @return 设备信息
     */
    @Override
    public TDevice selectTDeviceById(String id) {
        return tDeviceMapper.selectTDeviceById(id);
    }

    /**
     * 查询设备信息列表
     *
     * @param tDevice 设备信息
     * @return 设备信息
     */
    @Override
    public List<TDevice> selectTDeviceList(TDevice tDevice) {
        List<TDevice> deviceList = tDeviceMapper.selectTDeviceList(tDevice);
        if (!CollectionUtils.isEmpty(deviceList)) {
            // 收集所有需要查询的unitId
            List<String> unitIds = deviceList.stream()
                    .filter(device -> device.getUnitId() != null)
                    .map(TDevice::getUnitId)
                    .distinct()
                    .collect(Collectors.toList());

            if (!CollectionUtils.isEmpty(unitIds)) {
                try {
                    // 批量获取单位信息
                    List<TUnit> unitList = unitService.listByIds(unitIds);
                    if (!CollectionUtils.isEmpty(unitList)) {
                        // 建立unitId到Unit对象的映射关系
                        Map<String, TUnit> unitMap = unitList.stream()
                                .filter(Objects::nonNull)
                                .filter(unit -> unit.getId() != null)
                                .collect(Collectors.toMap(TUnit::getId, unit -> unit, (existing, replacement) -> existing));

                        // 为设备设置对应的单位信息
                        deviceList.forEach(device -> {
                            if (device.getUnitId() != null) {
                                TUnit unit = unitMap.get(device.getUnitId());
                                if (unit != null) {
                                    device.setUnitInfo(unit);
                                }
                            }
                        });
                    }
                } catch (Exception e) {
                    // 记录异常日志，但不中断主流程
                    log.error("批量查询单位信息失败", e);
                }
            }
        }
        return deviceList;
    }

    /**
     * 新增设备信息
     *
     * @param tDevice 设备信息
     * @return 结果
     */
    @Override
    public boolean insertTDevice(TDevice tDevice) {

        List<SysDictData> dictDeviceNameDataList = dictTypeService.selectDictDataByType("device_name");
        List<SysDictData> dictDeviceAddressDataList = dictTypeService.selectDictDataByType("device_address");

        TUnit tUnit = unitService.getById(tDevice.getUnitId());

        boolean isNetworkedUnit = tUnit.getUnitId() != null;

        tDevice.setPushStatus(PushStatus.NOT_PUSHED.getCode());

        Long userId = SecurityUtils.getUserId();
        String username = SecurityUtils.getUsername();
        tDevice.setCreateBy(username);
        tDevice.setCreateTime(DateUtils.getNowDate());
        tDevice.setCreateUserId(userId);

        boolean result = save(tDevice);
        if (result && isNetworkedUnit) {
            // 提交至线程池异步处理推送逻辑
            threadPoolTaskExecutor.execute(() -> {
                try {

                    // 安全地查找设备名称对应的标签
                    Optional<SysDictData> dictDeviceNameOpt = dictDeviceNameDataList.stream()
                            .filter(dictData -> dictData.getDictValue().equals(tDevice.getDeviceName()))
                            .findFirst();
                    if (!dictDeviceNameOpt.isPresent()) {
                        throw new IllegalArgumentException("无效的设备名称：" + tDevice.getDeviceName());
                    }
                    tDevice.setDeviceName(dictDeviceNameOpt.get().getDictLabel());

                    // 修复：使用正确的字段 deviceAddress 进行过滤
                    Optional<SysDictData> dictDeviceAddressOpt = dictDeviceAddressDataList.stream()
                            .filter(dictData -> dictData.getDictValue().equals(tDevice.getDeviceAddress()))
                            .findFirst();
                    if (!dictDeviceAddressOpt.isPresent()) {
                        throw new IllegalArgumentException("无效的设备地址：" + tDevice.getDeviceAddress());
                    }
                    tDevice.setDeviceAddress(dictDeviceAddressOpt.get().getDictLabel());

                    Map<String, Object> deviceMap = ConvertToMap.convertObjectToMap(tDevice);
                    deviceMap.remove("id");
                    deviceMap.put("unit_id", tUnit.getUnitId());
                    ResponseEntityInfo responseEntityInfo = requestService.advancedRequest(RequestMapper.ADD_DEVICE, deviceMap);

                    TDevice device = JSON.parseObject(responseEntityInfo.getData().toString(), TDevice.class);

                    LambdaUpdateWrapper<TDevice> updateWrapper = Wrappers.lambdaUpdate(TDevice.class)
                            .eq(TDevice::getId, tDevice.getId())
                            .set(TDevice::getPushStatus, PushStatus.PUSH_SUCCESSFUL.getCode())
                            .set(TDevice::getDeviceId, device.getId());
                    update(updateWrapper);
                } catch (Exception e) {
                    log.error("推送设备信息失败: id={}, error={}", tDevice.getId(), e.getMessage(), e);

                    // 更新推送状态为失败
                    LambdaUpdateWrapper<TDevice> failUpdateWrapper = Wrappers.lambdaUpdate(TDevice.class)
                            .eq(TDevice::getId, tDevice.getId())
                            .set(TDevice::getPushStatus, PushStatus.PUSH_FAILED.getCode());
                    update(failUpdateWrapper);
                }
            });
        }
        return result;
    }

    /**
     * 修改设备信息
     *
     * @param tDevice 设备信息
     * @return 结果
     */
    @Override
    public int updateTDevice(TDevice tDevice) {

        TUnit tUnit = unitService.getById(tDevice.getUnitId());

        boolean isNetworkedUnit = UnitType.NETWORKED_UNITS.getCode().equals(tUnit.getUnitType());

        // 设置推送状态
        if (!isNetworkedUnit) {
            tDevice.setPushStatus(PushStatus.NOT_PUSHED.getCode());
        }

        tDevice.setUpdateTime(DateUtils.getNowDate());
        int result = tDeviceMapper.updateTDevice(tDevice);

        List<SysDictData> dictDeviceNameDataList = dictTypeService.selectDictDataByType("device_name");
        List<SysDictData> dictDeviceAddressDataList = dictTypeService.selectDictDataByType("device_address");

        if (result > 0 && isNetworkedUnit) {
            // 提交至线程池异步处理推送逻辑
            threadPoolTaskExecutor.execute(() -> {
                try {

                    // 安全地查找设备名称对应的标签
                    Optional<SysDictData> dictDeviceNameOpt = dictDeviceNameDataList.stream()
                            .filter(dictData -> dictData.getDictValue().equals(tDevice.getDeviceName()))
                            .findFirst();
                    if (!dictDeviceNameOpt.isPresent()) {
                        throw new IllegalArgumentException("无效的设备名称：" + tDevice.getDeviceName());
                    }
                    tDevice.setDeviceName(dictDeviceNameOpt.get().getDictLabel());

                    // 修复：使用正确的字段 deviceAddress 进行过滤
                    Optional<SysDictData> dictDeviceAddressOpt = dictDeviceAddressDataList.stream()
                            .filter(dictData -> dictData.getDictValue().equals(tDevice.getDeviceAddress()))
                            .findFirst();
                    if (!dictDeviceAddressOpt.isPresent()) {
                        throw new IllegalArgumentException("无效的设备地址：" + tDevice.getDeviceAddress());
                    }
                    tDevice.setDeviceAddress(dictDeviceAddressOpt.get().getDictLabel());

                    RequestMapper requestMapper = tDevice.getDeviceId() != null ? RequestMapper.UPDATE_DEVICE : RequestMapper.ADD_DEVICE;
                    Map<String, Object> buildingMap = ConvertToMap.convertObjectToMap(tDevice);
                    if (tDevice.getDeviceId() != null) {
                        buildingMap.put("id", tDevice.getDeviceId());
                    } else {
                        buildingMap.remove("id");
                    }
                    ResponseEntityInfo responseEntityInfo = requestService.advancedRequest(requestMapper, buildingMap);

                    TDevice device = JSON.parseObject(responseEntityInfo.getData().toString(), TDevice.class);

                    LambdaUpdateWrapper<TDevice> updateWrapper = Wrappers.lambdaUpdate(TDevice.class)
                            .eq(TDevice::getId, tDevice.getId())
                            .set(TDevice::getPushStatus, PushStatus.PUSH_SUCCESSFUL.getCode())
                            .set(TDevice::getDeviceId, device.getId());
                    update(updateWrapper);
                } catch (Exception e) {
                    log.error("推送设备信息失败: deviceId={}, error={}", tDevice.getId(), e.getMessage(), e);

                    // 更新推送状态为失败
                    LambdaUpdateWrapper<TDevice> failUpdateWrapper = Wrappers.lambdaUpdate(TDevice.class)
                            .eq(TDevice::getId, tDevice.getId())
                            .set(TDevice::getPushStatus, PushStatus.PUSH_FAILED.getCode());
                    update(failUpdateWrapper);
                }
            });
        }
        return result;
    }

    /**
     * 批量删除设备信息
     *
     * @param ids 需要删除的设备信息主键
     * @return 结果
     */
    @Override
    public int deleteTDeviceByIds(String[] ids) {
        return tDeviceMapper.deleteTDeviceByIds(ids);
    }

    /**
     * 删除设备信息信息
     *
     * @param id 设备信息主键
     * @return 结果
     */
    @Override
    public int deleteTDeviceById(String id) {
        return tDeviceMapper.deleteTDeviceById(id);
    }

    /**
     * 删除设备信息信息
     *
     * @param id 设备信息主键
     * @return 结果
     */
    @Override
    public boolean pushDevice(String id) {
        TDevice device = getById(id);
        if (device == null) {
            log.warn("设备信息不存在，id={}", id);
            return false;
        }

        boolean isNew = device.getDeviceId() == null || device.getDeviceId().equals("");

        doPush(isNew, device);
        return true;
    }

    /**
     * 获取设备列表
     *
     * @param deviceStatus 设备状态
     * @return 结果
     */
    @Override
    public List<TDevice> enableDeviceList(DeviceStatus deviceStatus) {
        LambdaQueryWrapper<TDevice> wrapper = Wrappers.lambdaQuery(TDevice.class);
        wrapper.eq(TDevice::getDeviceStatus, deviceStatus.getCode());
        return list(wrapper);
    }

    /**
     * 获取设备列表
     *
     * @param deviceStatus 设备状态
     * @return 结果
     */
    @Override
    public List<TDevice> enableDeviceWatchPushList(DeviceStatus deviceStatus, DeviceCategory deviceCategory) {
        LambdaQueryWrapper<TDevice> wrapper = Wrappers.lambdaQuery(TDevice.class);
        wrapper.eq(TDevice::getDeviceStatus, deviceStatus.getCode());
        wrapper.eq(TDevice::getDeviceCategory, deviceCategory.getCode());
        return list(wrapper);
    }

    /**
     * 获取设备列表
     *
     * @param deviceStatus 设备状态
     * @return 结果
     */
    @Override
    public List<TDevice> enableDeviceWatchPushList(DeviceStatus deviceStatus, DeviceCategory deviceCategory, PushStatus pushStatus) {
        LambdaQueryWrapper<TDevice> wrapper = Wrappers.lambdaQuery(TDevice.class);
        wrapper.eq(TDevice::getDeviceStatus, deviceStatus.getCode());
        wrapper.eq(TDevice::getDeviceCategory, deviceCategory.getCode());
        wrapper.eq(TDevice::getPushStatus, pushStatus.getCode());
        return list(wrapper);
    }

    /**
     * 远程删除设备
     *
     * @param deviceIds 设备id
     * @return 删除结果
     */
    @Override
    public boolean remoteDeletion(String deviceIds) {
        TDevice device = getById(deviceIds);
        if (StringUtils.isNotNull(device)) {
            Map<String, Object> params = new HashMap<>();
            params.put("id", device.getDeviceId());
            ResponseEntityInfo responseEntityInfo = requestService.advancedRequest(RequestMapper.DEVICE_DELETE, params);

            if (responseEntityInfo.getErrno() == 0) {
                LambdaUpdateWrapper<TDevice> updateWrapper = Wrappers.lambdaUpdate(TDevice.class);
                updateWrapper.set(TDevice::getDeviceId, "").set(TDevice::getDeviceStatus, DeviceStatus.DISABLE.getCode());
                updateWrapper.set(TDevice::getPushStatus, PushStatus.NOT_PUSHED.getCode());
                updateWrapper.eq(TDevice::getId, device.getId());
                update(updateWrapper);
            } else {
                throw new ServiceException("远程删除失败： " + responseEntityInfo.getErrmsg());
            }
        }
        return true;
    }

    /**
     * 模拟数据同步
     *
     * @param deviceId  设备id
     * @param dataValue 数据值
     * @return 同步结果
     */
    @Override
    public void fakeDataSynchronization(String deviceId, String dataValue) {
        TDevice device = getById(deviceId);
        if (StringUtils.isNotNull(device)) {
            processDeviceData(device, dataValue);
        }
    }

    /**
     * 删除设备信息信息
     *
     * @param deviceId 设备信息主键
     * @return 删除结果
     */
    @Override
    public int removeByDeviceId(String deviceId) {
        TDevice device = getById(deviceId);
        if (StringUtils.isNotNull(device) && StringUtils.isNotEmpty(device.getDeviceId())) {
            Map<String, Object> params = new HashMap<>();
            params.put("id", device.getDeviceId());
            ResponseEntityInfo responseEntityInfo = requestService.advancedRequest(RequestMapper.DEVICE_DELETE, params);

            if (responseEntityInfo.getErrno() == 0) {
                removeById(deviceId);
            }
            throw new ServiceException("远程删除失败： " + responseEntityInfo.getErrmsg());
        }
        return 0;
    }

    private void processDeviceData(TDevice device, String dataValue) {
        if (DeviceCategory.GATEWAY.getCode().equals(device.getDeviceCategory())) {
            handleGatewayDevice(device, dataValue);
        } else {
            handleWaterDevice(device, dataValue);
        }
    }

    private void handleGatewayDevice(TDevice device, String dataValue) {
        // 查询最近一次上报的数据
        DGatewayMessage dGatewayMessage = gatewayMessageService.selectLastOneByDeviceNo(device.getDeviceCode());

        // 网关协议
        Map<String, Object> params = new HashMap<>();
        // 设备id,创建设备时获得
        params.put("device_id", device.getDeviceId());

//        if (StringUtils.isNull(dGatewayMessage)) {
        // 报警状态，0-正常，1-报警  PS是火警是报警  其他为正常
        if (StringUtils.containsAny(GATEWAY_FIRE_TYPES, dataValue)) {
            params.put("alarm_status", 1);
        } else {
            params.put("alarm_status", 0);
        }
//        } else {
//            // 报警状态，0-正常，1-报警  PS是火警是报警  其他为正常
//            if (dGatewayMessage.getPS().equals(dataValue)) {
//                params.put("alarm_status", 1);
//            } else {
//                params.put("alarm_status", 0);
//            }
//        }

//        if (StringUtils.isNull(dGatewayMessage)) {
        // 故障状态，0-正常，1-故障 PS是故障是故障 其他为正常
        if (StringUtils.containsAny(GATEWAY_FAULT_TYPES, dataValue)) {
            params.put("abnormal_status", 1);
        } else {
            params.put("abnormal_status", 0);
        }
//        } else {
//            // 故障状态，0-正常，1-故障 PS是故障是故障 其他为正常
//            if (dGatewayMessage.getPS().equals(dataValue)) {
//                params.put("abnormal_status", 1);
//            } else {
//                params.put("abnormal_status", 0);
//            }
//        }

        // 屏蔽状态，0-正常，1-异常 都是正常
        params.put("shield_status", 0);
        // 事件发生时间，毫秒级时间戳，格式 1539776909000
        params.put("reported_at", System.currentTimeMillis());

        Map<String, Object> childData = new HashMap<>();

//        if (StringUtils.isNull(dGatewayMessage)) {
        childData.put("data_type_id", 42);
//        } else {
//            String pt = dGatewayMessage.getPT();
//            if (StringUtils.containsAny(GATEWAY_FAULT_TYPES, pt)) {
//                childData.put("data_type_id", 15);
//            } else if (StringUtils.containsAny(GATEWAY_RESET_TYPES, pt)) {
//                childData.put("data_type_id", 16);
//            } else if (StringUtils.containsAny(GATEWAY_OTHER_TYPES, pt)) {
//                childData.put("data_type_id", 42);
//            } else if (StringUtils.containsAny(GATEWAY_FIRE_TYPES, pt)) {
//                childData.put("data_type_id", 84);
//            }
//        }

        // data_value PT的值
        childData.put("data_value", dataValue);

//        if (StringUtils.isNull(dGatewayMessage)) {
        // alarm_status PS 为火警为报警 其他为正常
        if (StringUtils.containsAny(GATEWAY_FIRE_TYPES, dataValue)) {
            childData.put("alarm_status", 1);
        } else {
            childData.put("alarm_status", 0);
        }
//        } else {
//            // alarm_status PS 为火警为报警 其他为正常
//            if (dGatewayMessage.getPS().equals(dataValue)) {
//                childData.put("alarm_status", 1);
//            } else {
//                childData.put("alarm_status", 0);
//            }
//        }

//        if (StringUtils.isNull(dGatewayMessage)) {
        // abnormal_status PS为故障为故障 其他为正常
        if (StringUtils.containsAny(GATEWAY_FAULT_TYPES, dataValue)) {
            childData.put("abnormal_status", 1);
        } else {
            childData.put("abnormal_status", 0);
        }
//        } else {
//            // abnormal_status PS为故障为故障 其他为正常
//            if (dGatewayMessage.getPS().equals(dataValue)) {
//                childData.put("abnormal_status", 1);
//            } else {
//                childData.put("abnormal_status", 0);
//            }
//        }

        // threshold_const_value
        childData.put("threshold_const_value", "");
        childData.put("threshold_max_value", "");
        childData.put("threshold_min_value", "");

        List<Map<String, Object>> dataList = new ArrayList<>(1);
        dataList.add(childData);

        params.put("data", JSON.toJSONString(dataList));

        requestService.advancedRequest(RequestMapper.DYNAMIC_DATA_UPLOAD, params);
    }

    private void handleWaterDevice(TDevice device, String dataValue) {
        // 水协议
        DWaterMessage waterMessage = waterMessageService.selectLastOneByDeviceNo(device.getDeviceCode());

        Map<String, Object> params = new HashMap<>();
        // 设备id,创建设备时获得
        params.put("device_id", device.getDeviceId());
        // 报警状态，0-正常，1-报警  都是正常
        params.put("alarm_status", 0);
        // 故障状态，0-正常，1-故障 都是正常
        params.put("abnormal_status", 0);
        // 屏蔽状态，0-正常，1-异常 都是正常
        params.put("shield_status", 0);
        // 事件发生时间，毫秒级时间戳，格式 1539776909000
        params.put("reported_at", System.currentTimeMillis());

        Map<String, Object> childData = new HashMap<>();

        String deviceName = device.getDeviceName();
        if (WATER_POOL_TANK_TYPES.contains(deviceName)) {
            // 水池水箱 单位 米
            childData.put("data_type_id", 2);
        } else if (WATER_SYSTEM_TYPES.contains(deviceName)) {
            // 消火栓/喷淋 单位 压力
            childData.put("data_type_id", 1);
        }

        if (StringUtils.isNull(waterMessage)) {
            childData.put("data_value", dataValue);

            if (StringUtils.isNotEmpty(device.getDeviceMax())) {
                // 阈值上限，data_model=0时 （模拟量）
                childData.put("threshold_max_value", device.getDeviceMax());
            } else {
                throw new ServiceException("阈值上限为空");
            }

            if (StringUtils.isNotEmpty(device.getDeviceMin())) {
                // 阈值下限，data_model=0时 （模拟量）
                childData.put("threshold_min_value", device.getDeviceMin());
            } else {
                throw new ServiceException("阈值下限为空");
            }
        } else {
            processWaterDeviceData(childData, waterMessage, device);
        }


        // 是否达到报警状态 都是0
        childData.put("alarm_status", 0);
        // 是否是异常状态 都是0
        childData.put("abnormal_status", 0);
        // data_model 0-水协议 1-网关协议
        childData.put("data_model", 0);

        List<Map<String, Object>> dataList = new ArrayList<>(1);
        dataList.add(childData);

        params.put("data", JSON.toJSONString(dataList));
        requestService.advancedRequest(RequestMapper.DYNAMIC_DATA_UPLOAD, params);
    }

    private void processWaterDeviceData(Map<String, Object> childData, DWaterMessage waterMessage, TDevice device) {
        String deviceName = device.getDeviceName();

        Optional<DWaterDeviceMessage> messageOpt = Optional.empty();
        if (WATER_POOL_TANK_TYPES.contains(deviceName)) {
            // 水池/水箱 数据项值 液位值 field4 A1
            messageOpt = waterMessage.getWaterDeviceMessages().stream()
                    .filter(item -> "A1".equals(item.getDevice()))
                    .findFirst();
        } else if (HYDRANT_TYPES.contains(deviceName)) {
            // 消火栓 数据项值 液位值 field4 A2
            messageOpt = waterMessage.getWaterDeviceMessages().stream()
                    .filter(item -> "A2".equals(item.getDevice()))
                    .findFirst();
        } else if (SPRINKLER_TYPES.contains(deviceName)) {
            // 喷淋 数据项值 液位值 field4 A3
            messageOpt = waterMessage.getWaterDeviceMessages().stream()
                    .filter(item -> "A3".equals(item.getDevice()))
                    .findFirst();
        }

        if (messageOpt.isPresent()) {
            DWaterDeviceMessage dWaterDeviceMessage = messageOpt.get();
            childData.put("data_value", dWaterDeviceMessage.getField4());

            if (StringUtils.isNotEmpty(device.getDeviceMax())) {
                // 阈值上限，data_model=0时 （模拟量）
                childData.put("threshold_max_value", device.getDeviceMax());
            } else {
                childData.put("threshold_max_value", dWaterDeviceMessage.getField6());
            }

            if (StringUtils.isNotEmpty(device.getDeviceMin())) {
                // 阈值下限，data_model=0时 （模拟量）
                childData.put("threshold_min_value", device.getDeviceMin());
            } else {
                childData.put("threshold_min_value", dWaterDeviceMessage.getField5());
            }
        }
    }


    private void doPush(boolean isNew, TDevice device) {
        String requestType = isNew ? "新增设备信息" : "修改设备信息";
        log.info("开始{}推送，unitId={}", requestType, device.getId());

        Map<String, Object> deviceMap = ConvertToMap.convertObjectToMap(device);
        if (isNew) {
            TUnit unit = unitService.getById(device.getUnitId());
            deviceMap.remove("id");
            deviceMap.put("unit_id", unit.getUnitId());
        } else {
            deviceMap.put("id", device.getDeviceId());
        }

        List<SysDictData> dictDeviceNameDataList = dictTypeService.selectDictDataByType("device_name");
        List<SysDictData> dictDeviceAddressDataList = dictTypeService.selectDictDataByType("device_address");


        // 安全地查找设备名称对应的标签
        Optional<SysDictData> dictDeviceNameOpt = dictDeviceNameDataList.stream()
                .filter(dictData -> dictData.getDictValue().equals(device.getDeviceName()))
                .findFirst();
        if (!dictDeviceNameOpt.isPresent()) {
            throw new IllegalArgumentException("无效的设备名称：" + device.getDeviceName());
        }
        device.setDeviceName(dictDeviceNameOpt.get().getDictLabel());

        // 修复：使用正确的字段 deviceAddress 进行过滤
        Optional<SysDictData> dictDeviceAddressOpt = dictDeviceAddressDataList.stream()
                .filter(dictData -> dictData.getDictValue().equals(device.getDeviceAddress()))
                .findFirst();
        if (!dictDeviceAddressOpt.isPresent()) {
            throw new IllegalArgumentException("无效的设备地址：" + device.getDeviceAddress());
        }
        device.setDeviceAddress(dictDeviceAddressOpt.get().getDictLabel());

        RequestMapper mapper = isNew ? RequestMapper.ADD_DEVICE : RequestMapper.UPDATE_DEVICE;
        ResponseEntityInfo responseEntityInfo = requestService.advancedRequest(mapper, deviceMap);

        if (responseEntityInfo.getErrno() != 0) {
            log.error("{}推送失败，unitId={}, error={}", requestType, device.getId(), responseEntityInfo.getErrmsg());

            // 推送失败
            LambdaUpdateWrapper<TDevice> failUpdateWrapper = Wrappers.lambdaUpdate(TDevice.class)
                    .eq(TDevice::getId, device.getId())
                    .set(TDevice::getPushStatus, PushStatus.PUSH_FAILED.getCode());

            update(failUpdateWrapper);
            throw new ServiceException(responseEntityInfo.getErrmsg());
        }

        TDevice deviceResult = JSON.parseObject(responseEntityInfo.getData().toString(), TDevice.class);

        LambdaUpdateWrapper<TDevice> updateWrapper = Wrappers.lambdaUpdate(TDevice.class)
                .eq(TDevice::getId, device.getId())
                .set(TDevice::getPushStatus, PushStatus.PUSH_SUCCESSFUL.getCode())
                .set(TDevice::getDeviceId, deviceResult.getId());

        update(updateWrapper);

        log.info("{}推送成功，unitId={}", requestType, device.getId());
    }
}
